package com.csliubo.eclipse.plugin.sqlgenerator.core.writer;

import java.io.File;
import java.io.FileOutputStream;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import com.csliubo.eclipse.plugin.sqlgenerator.core.model.Row;
import com.csliubo.eclipse.plugin.sqlgenerator.core.model.Table;

/**
 * 
 * @author liubo
 * 
 */
public class ExcelWriter implements DataWriter {
	private static final String EXCEL_EXTENSION = ".xls";

	private void writeSheet(HSSFWorkbook wb, Table table) {
		String sheetName = table.getName();
		List<Row> rows = table.getRows();
		HSSFSheet sheet = wb.createSheet(sheetName);
		int rowSize = rows.size();
		for (int i = 0; i < rowSize; i++) {
			Row row = rows.get(i);
			HSSFRow hssfRow = sheet.createRow(i);
			List<String> columns = row.getColumns();
			int columnSize = columns.size();
			for (int j = 0; j < columnSize; j++) {
				HSSFCell cell = hssfRow.createCell((short) j);
				HSSFRichTextString richStr = new HSSFRichTextString(
						columns.get(j));
				cell.setCellValue(richStr);
			}
		}
	}

	public void write(String fileName, List<Table> tables) throws Throwable {
		File file = new File(fileName + EXCEL_EXTENSION);
		if (!file.exists()) {
			file.createNewFile();
		}
		HSSFWorkbook wb = null;
		wb = new HSSFWorkbook();
		FileOutputStream fis = new FileOutputStream(file);

		for (Table table : tables) {
			writeSheet(wb, table);
		}
		wb.write(fis);
		fis.flush();
		fis.close();
	}
}
